<template>
  <el-dialog v-model="visible" title="申请客户退住" width="500px" :close-on-click-modal="false">
    <el-form ref="formRef" :model="form.data" :rules="form.rules" label-width="100px" v-loading="loading">
      <el-form-item label="申请客户">
        <el-input :value="clientName" disabled />
      </el-form-item>
      <el-form-item label="退住类型" prop="checkOutType">
        <el-select v-model="form.data.checkOutType" placeholder="请选择退住类型" style="width:100%">
          <el-option label="正常退住" value="正常退住"/>
          <el-option label="死亡退住" value="死亡退住"/>
          <el-option label="保留床位" value="保留床位"/>
        </el-select>
      </el-form-item>
      <el-form-item label="退住时间" prop="checkOutTime">
        <el-date-picker
            v-model="form.data.checkOutTime"
            type="datetime"
            placeholder="选择退住时间"
            style="width:100%"
        />
      </el-form-item>
      <el-form-item label="退住原因" prop="checkOutReason">
        <el-input
            v-model="form.data.checkOutReason"
            type="textarea"
            :rows="3"
            placeholder="请输入详细的退住原因"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible=false">取消</el-button>
      <el-button type="primary" @click="submit" :loading="loading">提交申请</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { applyForCheckOut } from '@/api/apiList/checkOut.js'; // 导入API

const emit = defineEmits(['success']);

const visible = ref(false);
const loading = ref(false);
const formRef = ref(null);
const clientName = ref('');

// --- 表单数据和规则 ---
const getInitialForm = () => ({
  clientId: null,
  checkOutType: '正常退住',
  checkOutTime: new Date(),
  checkOutReason: ''
});

const form = reactive({
  data: getInitialForm(),
  rules: {
    checkOutType: [{ required: true, message: '请选择退住类型', trigger: 'change' }],
    checkOutTime: [{ required: true, message: '请选择退住时间', trigger: 'change' }],
    checkOutReason: [{ required: true, message: '请输入退住原因', trigger: 'blur' }],
  }
});

// --- 方法 ---

// open方法，由父组件调用
const open = (client) => {
  Object.assign(form.data, getInitialForm());
  form.data.clientId = client.clientId;
  clientName.value = client.clientName;
  if (formRef.value) formRef.value.clearValidate();
  visible.value = true;
};

// 提交表单
const submit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      await applyForCheckOut(form.data);
      ElMessage.success('退住申请提交成功');
      visible.value = false;
      emit('success'); // 通知父组件刷新列表或执行其他操作
    } catch(e) {
      console.error("提交退住申请失败:", e);
    }
    finally {
      loading.value = false;
    }
  });
};

// 将open方法暴露给父组件
defineExpose({ open });
</script>
